package Utils;

import java.security.MessageDigest;

public class Criptografia {

    public static String criptografarString(String strOriginal) throws Exception {
	String strCripto = null;
	try {

	    MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone();

	    // encode the credentials
	    md.update(strOriginal.getBytes());

	    // Digest the credentials and return as hexadecimal
	    strCripto = convert(md.digest());

	} catch (Exception e) {
	    throw e;
	}
	return strCripto;
    }

    /**
     * Convert a byte array into a printable format containing a String of
     * hexadecimal digit characters (two per byte). 
     * @param bytes Byte array representation
     */
    public static String convert(byte bytes[]) {

	StringBuffer sb = new StringBuffer(bytes.length * 2);
	for (int i = 0; i < bytes.length; i++) {
	    sb.append(convertDigit((int) (bytes[i] >> 4)));
	    sb.append(convertDigit((int) (bytes[i] & 0x0f)));
	}
	return (sb.toString());

    }

    /**
     * [Private] Convert the specified value (0 .. 15) to the corresponding
     * hexadecimal digit.
     * @param value Value to be converted
     */
    private static char convertDigit(int value) {

	value &= 0x0f;
	if (value >= 10)
	    return ((char) (value - 10 + 'a'));
	else
	    return ((char) (value + '0'));
    }
}